﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace XcoAppSpaces.Core.Communication
{
    class Timer : IDisposable
    {
	    private readonly Action _action;
	    private readonly int _interval;
		//private bool _running = true;
	    private readonly CancellationTokenSource cts;

		public Timer(Action action, int interval)
		{
			_action = action;
			_interval = interval;

			cts = new CancellationTokenSource();
			
			StartTimer();
		}

	    private void StartTimer()
	    {
		    if (cts.IsCancellationRequested)
		    {
				cts.Dispose();
			    return;
		    }
		    Task.Delay(_interval, cts.Token).ContinueWith(_ => TimerAction(), TaskContinuationOptions.ExecuteSynchronously | TaskContinuationOptions.OnlyOnRanToCompletion);
	    }

	    private void TimerAction()
	    {
			if (cts.IsCancellationRequested)
			{
				cts.Dispose();
				return;
			}
		    _action();

		    StartTimer();
	    }

	    public void Dispose()
		{
			cts.Cancel();
		}
	}
}
